{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": []
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "# How to Leverage OpenAI Function Calling for Financial Data Retrieval?\n",
        "\n",
        "Looking to retrieve financial company information efficiently? Here’s a quick breakdown of how you can use OpenAI's function calling:\n",
        "\n",
        "\n",
        "**1.   Define Your Functions:**\n",
        "\n",
        "Begin by integrating external APIs and specifying the exact data you want to pull from them.\n",
        "\n",
        "**2.   Set Up Function Schemas:**\n",
        "\n",
        "For each function, provide essential details such as the function name, description, and the parameters required (e.g., properties, types).\n",
        "\n",
        "**3.   Invoke the Model: I used GPT-4o-mini**\n",
        "\n",
        "Use the chat completion method, passing in the function parameters, and set function_call=auto to let the model determine when to call the functions.\n",
        "\n",
        "\n",
        "The entire process is outlined clearly in the notebook for easy implementation!"
      ],
      "metadata": {
        "id": "qWVzSHAS3_4v"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!pip install openai -q"
      ],
      "metadata": {
        "id": "0aktEqa0u9Ed"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "Specify the API Keys"
      ],
      "metadata": {
        "id": "yf5-txDBv9Ds"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "from google.colab import userdata\n",
        "OPENAI_API_KEY = userdata.get('OPENAI_API_KEY')\n",
        "FINANCIAL_MODELING_PREP_API_KEY = userdata.get('FINANCIAL_MODELING_PREP_API_KEY')\n",
        "\n",
        "import os\n",
        "import requests\n",
        "\n",
        "from openai import OpenAI\n",
        "client = OpenAI(api_key=OPENAI_API_KEY)"
      ],
      "metadata": {
        "id": "J7cO6pDowA3U"
      },
      "execution_count": 3,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Define Your Functions"
      ],
      "metadata": {
        "id": "GNqYdJLB2zno"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "def get_stock_price(symbol):\n",
        "    \"\"\"\n",
        "    Fetch the current stock price for the given symbol, the current volume, the average price 50d and 200d, EPS, PE and the next earnings Announcement.\n",
        "    \"\"\"\n",
        "    url = f\"https://financialmodelingprep.com/api/v3/quote-order/{symbol}?apikey={FINANCIAL_MODELING_PREP_API_KEY}\"\n",
        "    response = requests.get(url)\n",
        "    data = response.json()\n",
        "    try:\n",
        "        price = data[0]['price']\n",
        "        volume = data[0]['volume']\n",
        "        priceAvg50 = data[0]['priceAvg50']\n",
        "        priceAvg200 = data[0]['priceAvg200']\n",
        "        eps = data[0]['eps']\n",
        "        pe = data[0]['pe']\n",
        "        earningsAnnouncement = data[0]['earningsAnnouncement']\n",
        "        return {\"symbol\": symbol.upper(), \"price\": price, \"volume\":volume,\"priceAvg50\":priceAvg50, \"priceAvg200\":priceAvg200, \"EPS\":eps, \"PE\":pe, \"earningsAnnouncement\":earningsAnnouncement }\n",
        "    except (IndexError, KeyError):\n",
        "        return {\"error\": f\"Could not fetch price for symbol: {symbol}\"}\n",
        "\n",
        "def get_company_financials(symbol):\n",
        "    \"\"\"\n",
        "    Fetch basic financial information for the given company symbol such as the industry, the sector, the name of the company, and the market capitalization.\n",
        "    \"\"\"\n",
        "    url = f\"https://financialmodelingprep.com/api/v3/profile/{symbol}?apikey={FINANCIAL_MODELING_PREP_API_KEY}\"\n",
        "    response = requests.get(url)\n",
        "    data = response.json()\n",
        "    try:\n",
        "        results = data[0]\n",
        "        financials = {\n",
        "            \"symbol\": results[\"symbol\"],\n",
        "            \"companyName\": results[\"companyName\"],\n",
        "            \"marketCap\": results[\"mktCap\"],\n",
        "            \"industry\": results[\"industry\"],\n",
        "            \"sector\": results[\"sector\"],\n",
        "            \"website\": results[\"website\"],\n",
        "            \"beta\":results[\"beta\"],\n",
        "            \"price\":results[\"price\"],\n",
        "        }\n",
        "        return financials\n",
        "    except (IndexError, KeyError):\n",
        "        return {\"error\": f\"Could not fetch financials for symbol: {symbol}\"}\n",
        "\n",
        "def get_income_statement(symbol):\n",
        "    \"\"\"\n",
        "    Fetch last income statement for the given company symbol such as revenue, gross profit, net income, EBITDA, EPS.\n",
        "    \"\"\"\n",
        "    url = f\"https://financialmodelingprep.com/api/v3/income-statement/{symbol}?period=annual&apikey={FINANCIAL_MODELING_PREP_API_KEY}\"\n",
        "    response = requests.get(url)\n",
        "    data = response.json()\n",
        "    try:\n",
        "        results = data[0]\n",
        "        financials = {\n",
        "            \"date\": results[\"date\"],\n",
        "            \"revenue\": results[\"revenue\"],\n",
        "            \"gross profit\": results[\"grossProfit\"],\n",
        "            \"net Income\": results[\"netIncome\"],\n",
        "            \"ebitda\": results[\"ebitda\"],\n",
        "            \"EPS\": results[\"eps\"],\n",
        "            \"EPS diluted\":results[\"epsdiluted\"]\n",
        "        }\n",
        "        return data, financials\n",
        "    except (IndexError, KeyError):\n",
        "        return {\"error\": f\"Could not fetch financials for symbol: {symbol}\"}"
      ],
      "metadata": {
        "id": "h8bz8LgE230g"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Set Up Function Schemas"
      ],
      "metadata": {
        "id": "e2w6cqLV24ln"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "# Define the function schemas for OpenAI\n",
        "functions = [\n",
        "    {\n",
        "        \"name\": \"get_stock_price\",\n",
        "        \"description\": \"Get the current stock price for a given company symbol.\",\n",
        "        \"parameters\": {\n",
        "            \"type\": \"object\",\n",
        "            \"properties\": {\n",
        "                \"symbol\": {\n",
        "                    \"type\": \"string\",\n",
        "                    \"description\": \"The stock ticker symbol, e.g., AAPL for Apple.\"\n",
        "                }\n",
        "            },\n",
        "            \"required\": [\"symbol\"],\n",
        "        },\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"get_company_financials\",\n",
        "        \"description\": \"Get basic financial information for a given company.\",\n",
        "        \"parameters\": {\n",
        "            \"type\": \"object\",\n",
        "            \"properties\": {\n",
        "                \"symbol\": {\n",
        "                    \"type\": \"string\",\n",
        "                    \"description\": \"The stock ticker symbol, e.g., GOOGL for Alphabet Inc.\"\n",
        "                }\n",
        "            },\n",
        "            \"required\": [\"symbol\"],\n",
        "        },\n",
        "    },\n",
        "    {\n",
        "        \"name\": \"get_income_statement\",\n",
        "        \"description\": \"Get the last income statement for a given company symbol.\",\n",
        "        \"parameters\": {\n",
        "            \"type\": \"object\",\n",
        "            \"properties\": {\n",
        "                \"symbol\": {\n",
        "                    \"type\": \"string\",\n",
        "                    \"description\": \"The stock ticker symbol, e.g., AMZN for Amazon.\"\n",
        "                }\n",
        "            },\n",
        "            \"required\": [\"symbol\"],\n",
        "        },\n",
        "    },\n",
        "]"
      ],
      "metadata": {
        "id": "RqyA-5l_29Y3"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Invoke the Model: GPT-4o-mini and CHAT"
      ],
      "metadata": {
        "id": "aFlZBFMD2_EH"
      }
    },
    {
      "cell_type": "code",
      "execution_count": 28,
      "metadata": {
        "id": "eWakpo9ss1gB",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2df406b1-b501-4372-8de5-3d3f1ebc5542"
      },
      "outputs": [
        {
          "output_type": "stream",
          "name": "stdout",
          "text": [
            "I'm your Financial Analyst Assistant! Ask me anything about stock prices, company financials, or income statement.\n",
            "\n",
            "You: What is the last price of Amazon?\n",
            "Assistant: The last price of Amazon (AMZN) is $191.60.\n",
            "\n",
            "You: what was the income revenue of NVIDIA?\n",
            "Assistant: NVIDIA's revenue for the fiscal year 2024 was $60.92 billion.\n",
            "\n",
            "You: What was the last revenue reported by Apple?\n",
            "Assistant: Apple's last reported revenue for the fiscal year 2023 was $383.29 billion.\n",
            "\n",
            "You: What is the sector of AMD?\n",
            "Assistant: The sector of Advanced Micro Devices, Inc. (AMD) is Technology.\n",
            "\n",
            "You: exit\n",
            "Assistant: The discussion is terminated!\n"
          ]
        }
      ],
      "source": [
        "# Chat Function:\n",
        "MODEL_NAME = \"gpt-4o-mini\"\n",
        "def chat_with_LLM(model_name = MODEL_NAME):\n",
        "    messages = []\n",
        "    print(\"I'm your Financial Analyst Assistant! Ask me anything about stock prices, company financials, or income statement.\")\n",
        "    while True:\n",
        "        user_input = input(\"\\nYou: \")\n",
        "        if user_input.lower() in [\"exit\", \"quit\"]:\n",
        "            print(\"Assistant: The discussion is terminated!\")\n",
        "            break\n",
        "\n",
        "        messages.append({\"role\": \"user\", \"content\": user_input})\n",
        "\n",
        "        response = client.chat.completions.create(\n",
        "            model=MODEL_NAME,\n",
        "            messages=messages,\n",
        "            functions=functions,\n",
        "            function_call=\"auto\",  # Let the model decide if a function needs to be called\n",
        "        )\n",
        "\n",
        "        response_message = response.choices[0].message\n",
        "\n",
        "        # Check if the assistant wants to call a function\n",
        "        if response_message.function_call:\n",
        "            function_name = response_message.function_call.name\n",
        "            arguments = response_message.function_call.arguments\n",
        "\n",
        "            # Parse the arguments\n",
        "            import json\n",
        "            args = json.loads(arguments)\n",
        "\n",
        "            # Call the appropriate function\n",
        "            if function_name == \"get_stock_price\":\n",
        "                function_response = get_stock_price(**args)\n",
        "            elif function_name == \"get_company_financials\":\n",
        "                function_response = get_company_financials(**args)\n",
        "            elif function_name == \"get_income_statement\":\n",
        "                function_response = get_income_statement(**args)\n",
        "            else:\n",
        "                function_response = {\"error\": \"Function not found.\"}\n",
        "\n",
        "            # Add the function's response to the conversation\n",
        "            messages.append(response_message)  # Assistant's function call\n",
        "            messages.append({\n",
        "                \"role\": \"function\",\n",
        "                \"name\": function_name,\n",
        "                \"content\": json.dumps(function_response),\n",
        "            })\n",
        "\n",
        "            # Get the assistant's final response\n",
        "            second_response = client.chat.completions.create(\n",
        "                model=MODEL_NAME,\n",
        "                messages=messages,\n",
        "            )\n",
        "\n",
        "            final_message = second_response.choices[0].message.content\n",
        "            print(f\"Assistant: {final_message}\")\n",
        "            messages.append({\"role\": \"assistant\", \"content\": final_message})\n",
        "        else:\n",
        "            # If no function call is needed, just output the assistant's message\n",
        "            assistant_reply = response_message.content\n",
        "            print(f\"Assistant: {assistant_reply}\")\n",
        "            messages.append({\"role\": \"assistant\", \"content\": assistant_reply})\n",
        "\n",
        "# Run the chat function\n",
        "if __name__ == \"__main__\":\n",
        "    chat_with_LLM()\n"
      ]
    }
  ]
}